package com.cal.utms.model.payment;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cal.utms.action.user_maintenance.LoginAction;
import com.cal.utms.dao.maintenance.CustomerDaoImpl;
import com.cal.utms.dao.maintenance.IssuerDaoImpl;
import com.cal.utms.dao.maintenance.NewFundDao;
import com.cal.utms.dao.payment.PaymentDaoImpl;
import com.cal.utms.dao.payment.PlacementSheetDaoImpl;
import com.cal.utms.dao.payment.ReceiptDaoImpl;
import com.cal.utms.dto.payment.PlacementRecordDto;
import com.cal.utms.dto.payment.PlacementSheetDto;
import com.cal.utms.entity.Customer;
import com.cal.utms.entity.CustomerBankAccount;
import com.cal.utms.entity.IssuerBankAccount;
import com.cal.utms.entity.Payment;
import com.cal.utms.entity.PlacementSheet;
import com.cal.utms.entity.PlacementSheetRecord;
import com.cal.utms.entity.Receipt;

public class PlacementSheetModel {

	SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
	PlacementSheetDaoImpl daoImpl = new PlacementSheetDaoImpl();
	NewFundDao fundDao = new NewFundDao();

	CustomerDaoImpl customerDaoImpl = new CustomerDaoImpl();
	IssuerDaoImpl issuerDaoImpl = new IssuerDaoImpl();
	PaymentDaoImpl paymentDaoImpl = new PaymentDaoImpl();
	ReceiptDaoImpl receiptDaoImpl = new ReceiptDaoImpl();

	public void savePalcementsheet(String transactions, PlacementSheetDto placementSheetDto) {

		try {
			PlacementSheet sheet = daoImpl.getPlacementSheetByFundDate(placementSheetDto.getFund(), format.parse(placementSheetDto.getDate()));
			if (sheet == null) {
				PlacementSheet placementSheet = new PlacementSheet();
				try {
					placementSheet.setDate(format.parse(placementSheetDto.getDate()));
					placementSheet.setFund(fundDao.getById(placementSheetDto.getFund()));
					placementSheet.setStatus("INITIAL");
					placementSheet.setUser(LoginAction.getCurrentLogingUser());

				} catch (ParseException e) {
					e.printStackTrace();
				}

				List<PlacementSheetRecord> sheetRecords = new ArrayList<PlacementSheetRecord>();
				if (transactions != null) {
					transactions = "{ \"transactions\" : ".concat(transactions) + " }";
					try {
						JSONObject jsonObject = new JSONObject(transactions);
						JSONArray jArray = jsonObject.getJSONArray("transactions");
						for (int i = 0; i < jArray.length(); i++) {
							JSONObject jObj = jArray.getJSONObject(i);
							PlacementSheetRecord record = new PlacementSheetRecord();
							record.setAmount(BigDecimal.valueOf(jObj.getDouble("amount")));
							record.setBankAccount(jObj.getInt("bank_id"));
							record.setNameofbank(jObj.getString("comingFromBank"));
							record.setCustomerId(jObj.getInt("customer_id"));
							record.setCustomer(jObj.getString("customer_name"));
							record.setCustomerType(jObj.getString("customer_type"));
							record.setMoneyInOut(jObj.getString("moneyInOut"));
							record.setPayReceNo(jObj.getString("payReceNo"));
							record.setPlacementSheet(placementSheet);
							sheetRecords.add(record);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				placementSheet.setPlacementSheetRecords(sheetRecords);

				Object object = daoImpl.savePlacementSheet(placementSheet);
				if (object instanceof Integer) {
					placementSheetDto.setId((Integer) object);
					placementSheetDto.setSuccess(true);
					placementSheetDto.setResulteMsg("SUCCESS");
				} else {
					placementSheetDto.setSuccess(false);
					placementSheetDto.setResulteMsg("There is some error returned from the server.");
				}
			} else {
				placementSheetDto.setSuccess(false);
				placementSheetDto.setResulteMsg("Have PlacementSheet");
			}

		} catch (ParseException e1) {
			e1.printStackTrace();
		}

	}

	public List<PlacementRecordDto> getRecordByFund(int fundid, String date) {

		List<PlacementRecordDto> dtos = new ArrayList<PlacementRecordDto>();
		try {
			PlacementSheet sheet = daoImpl.getPlacementSheetByFundDate(fundid, format.parse(date));
			List<Payment> payments = paymentDaoImpl.getConfirmedPayByFundNDate(fundid, format.parse(date));
			List<Receipt> receipts = receiptDaoImpl.getRtgsReceipt(fundid, format.parse(date));

			if (sheet == null) {
				PlacementSheet placementSheet = new PlacementSheet();
				placementSheet.setDate(format.parse(date));
				placementSheet.setFund(fundDao.getById(fundid));
				placementSheet.setStatus("INITIAL");
				placementSheet.setUser(LoginAction.getCurrentLogingUser());

				List<PlacementSheetRecord> recordDtos = new ArrayList<PlacementSheetRecord>();
				if (receipts.size() > 0) {
					for (Receipt receipt : receipts) {
						PlacementSheetRecord record = new PlacementSheetRecord();
						record.setAmount(receipt.getAmount());
						record.setBankAccount(receipt.getBankId());
						record.setNameofbank(receipt.getBankName());
						record.setCustomerId(receipt.getCustomerId());
						if (receipt.getCustomerType().equals("CUS")) {
							Customer customer = customerDaoImpl.getCustomerById(receipt.getCustomerId());
							if (customer.getAccountType().equals("C")) {
								record.setCustomer(customer.getSurname());
							} else {
								record.setCustomer(customer.getInitials() + " " + customer.getSurname());
							}
						}
						record.setCustomerType(receipt.getCustomerType());
						record.setMoneyInOut("IN");
						record.setPlacementSheet(placementSheet);
						record.setPayReceNo(receipt.getReceiptNo());
						recordDtos.add(record);
					}
				}

				if (payments.size() > 0) {
					for (Payment payment : payments) {
						PlacementSheetRecord record = new PlacementSheetRecord();
						record.setAmount(payment.getAmount());
						record.setBankAccount(Integer.parseInt(payment.getBankAccount()));
						record.setNameofbank(payment.getBankName());
						record.setCustomerId(payment.getCustomerId());
						if (payment.getCustomerType().equals("CUS")) {
							Customer customer = customerDaoImpl.getCustomerById(payment.getCustomerId());
							if (customer.getAccountType().equals("C")) {
								record.setCustomer(customer.getSurname());
							} else {
								record.setCustomer(customer.getInitials() + " " + customer.getSurname());
							}
						}
						record.setCustomerType(payment.getCustomerType());
						record.setMoneyInOut("OUT");
						record.setPlacementSheet(placementSheet);
						record.setPayReceNo(payment.getPaymentNo());
						recordDtos.add(record);

					}
				}
				placementSheet.setPlacementSheetRecords(recordDtos);

				Object object = daoImpl.savePlacementSheet(placementSheet);
				if (object instanceof Integer) {
					PlacementSheet savedplacementSheet = daoImpl.getPlacementSheetById((Integer) object);
					if (savedplacementSheet != null) {
						List<PlacementSheetRecord> list = savedplacementSheet.getPlacementSheetRecords();
						for (PlacementSheetRecord placementSheetRecord : list) {
							PlacementRecordDto recordDto = new PlacementRecordDto();
							recordDto.setId(placementSheetRecord.getId());
							recordDto.setAmount(placementSheetRecord.getAmount());
							recordDto.setCustomer_id(placementSheetRecord.getCustomerId());
							recordDto.setCustomer_type(placementSheetRecord.getCustomerType());
							recordDto.setBank_id(placementSheetRecord.getBankAccount());
							recordDto.setPlacementSheet(placementSheetRecord.getPlacementSheet().getId());
							recordDto.setPayReceNo(placementSheetRecord.getPayReceNo() != null ? placementSheetRecord.getPayReceNo() : null);
							if (placementSheetRecord.getCustomerType().equals("CUS")) {
								Customer customer = customerDaoImpl.getCustomerById(placementSheetRecord.getCustomerId());
								if (customer.getAccountType().equals("C")) {
									recordDto.setCustomer_name(customer.getSurname());
								} else {
									recordDto.setCustomer_name(customer.getInitials() + " " + customer.getSurname());
								}
								CustomerBankAccount account = customerDaoImpl.getAccountById(placementSheetRecord.getBankAccount());
								recordDto.setComingFromBank(account.getAccountNo().concat(" - " + account.getNameOfBank() + " (" + account.getBranch() + ")"));

							} else if (placementSheetRecord.getCustomerType().equals("ISU")) {
								recordDto.setCustomer_name((issuerDaoImpl.getById(placementSheetRecord.getCustomerId()).getName()));
								IssuerBankAccount account = issuerDaoImpl.getAccountById(placementSheetRecord.getBankAccount());
								recordDto.setComingFromBank(account.getAccountNo().concat(" - " + account.getNameOfBank() + " (" + account.getBarnch() + ")"));
							}
							recordDto.setMoneyInOut(placementSheetRecord.getMoneyInOut());
							dtos.add(recordDto);
						}
					}
				}
			} else {
				PlacementSheet perplacementSheet = daoImpl.getPlacementSheetById(sheet.getId());
				if (perplacementSheet != null) {
					List<PlacementSheetRecord> additolnalrecordDtos = new ArrayList<PlacementSheetRecord>();
					List<PlacementSheetRecord> list = perplacementSheet.getPlacementSheetRecords();
					List<String> payreciCode = new ArrayList<String>();
					for (PlacementSheetRecord placementSheetRecord : list) {
						if (placementSheetRecord.getPayReceNo() != null) {
							payreciCode.add(placementSheetRecord.getPayReceNo());
						}
						additolnalrecordDtos.add(placementSheetRecord);
					}

					for (Receipt receipt : receipts) {
						if (!payreciCode.contains(receipt.getReceiptNo())) {
							PlacementSheetRecord record = new PlacementSheetRecord();
							record.setAmount(receipt.getAmount());
							record.setBankAccount(receipt.getBankId());
							record.setNameofbank(receipt.getBankName());
							record.setCustomerId(receipt.getCustomerId());
							if (receipt.getCustomerType().equals("CUS")) {
								Customer customer = customerDaoImpl.getCustomerById(receipt.getCustomerId());
								if (customer.getAccountType().equals("C")) {
									record.setCustomer(customer.getSurname());
								} else {
									record.setCustomer(customer.getInitials() + " " + customer.getSurname());
								}
							}
							record.setCustomerType(receipt.getCustomerType());
							record.setMoneyInOut("IN");
							record.setPlacementSheet(perplacementSheet);
							record.setPayReceNo(receipt.getReceiptNo());
							additolnalrecordDtos.add(record);
						}
					}

					for (Payment payment : payments) {
						if (!payreciCode.contains(payment.getPaymentNo())) {

							PlacementSheetRecord record = new PlacementSheetRecord();
							record.setAmount(payment.getAmount());
							record.setBankAccount(Integer.parseInt(payment.getBankAccount()));
							record.setNameofbank(payment.getBankName());
							record.setCustomerId(payment.getCustomerId());
							if (payment.getCustomerType().equals("CUS")) {
								Customer customer = customerDaoImpl.getCustomerById(payment.getCustomerId());
								if (customer.getAccountType().equals("C")) {
									record.setCustomer(customer.getSurname());
								} else {
									record.setCustomer(customer.getInitials() + " " + customer.getSurname());
								}
							}
							record.setCustomerType(payment.getCustomerType());
							record.setMoneyInOut("OUT");
							record.setPlacementSheet(perplacementSheet);
							record.setPayReceNo(payment.getPaymentNo());
							additolnalrecordDtos.add(record);
						}
					}
					perplacementSheet.setPlacementSheetRecords(additolnalrecordDtos);
					Object object = daoImpl.updatePlacementSheet(perplacementSheet);
					if (object instanceof PlacementSheet) {
						PlacementSheet savedplacementSheet = daoImpl.getPlacementSheetById(perplacementSheet.getId());
						if (savedplacementSheet != null) {
							List<PlacementSheetRecord> list2 = savedplacementSheet.getPlacementSheetRecords();
							for (PlacementSheetRecord placementSheetRecord : list2) {
								PlacementRecordDto recordDto = new PlacementRecordDto();
								recordDto.setId(placementSheetRecord.getId());
								recordDto.setAmount(placementSheetRecord.getAmount());
								recordDto.setCustomer_id(placementSheetRecord.getCustomerId());
								recordDto.setCustomer_type(placementSheetRecord.getCustomerType());
								recordDto.setBank_id(placementSheetRecord.getBankAccount());
								recordDto.setPlacementSheet(placementSheetRecord.getPlacementSheet().getId());
								recordDto.setPayReceNo(placementSheetRecord.getPayReceNo() != null ? placementSheetRecord.getPayReceNo() : null);
								if (placementSheetRecord.getCustomerType().equals("CUS")) {
									Customer customer = customerDaoImpl.getCustomerById(placementSheetRecord.getCustomerId());
									if (customer.getAccountType().equals("C")) {
										recordDto.setCustomer_name(customer.getSurname());
									} else {
										recordDto.setCustomer_name(customer.getInitials() + " " + customer.getSurname());
									}
									CustomerBankAccount account = customerDaoImpl.getAccountById(placementSheetRecord.getBankAccount());
									recordDto.setComingFromBank(account.getAccountNo().concat(" - " + account.getNameOfBank() + " (" + account.getBranch() + ")"));

								} else if (placementSheetRecord.getCustomerType().equals("ISU")) {
									recordDto.setCustomer_name((issuerDaoImpl.getById(placementSheetRecord.getCustomerId()).getName()));
									IssuerBankAccount account = issuerDaoImpl.getAccountById(placementSheetRecord.getBankAccount());
									recordDto.setComingFromBank(account.getAccountNo().concat(" - " + account.getNameOfBank() + " (" + account.getBarnch() + ")"));
								}
								recordDto.setMoneyInOut(placementSheetRecord.getMoneyInOut());
								dtos.add(recordDto);
							}
						}
					}
				}
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}
		return dtos;
	}

	public void updatePalcementsheet(String transactions, PlacementSheetDto placementSheetDto, int plasementsheetid) {

		try {
			PlacementSheet sheet = daoImpl.getPlacementSheetByFundDate(placementSheetDto.getFund(), format.parse(placementSheetDto.getDate()));
			if (sheet.getId() == plasementsheetid) {

				sheet.setStatus("INITIAL");
				sheet.setUser(LoginAction.getCurrentLogingUser());

				List<PlacementSheetRecord> sheetRecords = new ArrayList<PlacementSheetRecord>();
				if (transactions != null) {
					transactions = "{ \"transactions\" : ".concat(transactions) + " }";
					try {
						JSONObject jsonObject = new JSONObject(transactions);
						JSONArray jArray = jsonObject.getJSONArray("transactions");
						for (int i = 0; i < jArray.length(); i++) {
							JSONObject jObj = jArray.getJSONObject(i);
							PlacementSheetRecord record = new PlacementSheetRecord();
							record.setAmount(BigDecimal.valueOf(jObj.getDouble("amount")));
							record.setBankAccount(jObj.getInt("bank_id"));
							record.setNameofbank(jObj.getString("comingFromBank"));
							record.setCustomerId(jObj.getInt("customer_id"));
							record.setCustomer(jObj.getString("customer_name"));
							record.setCustomerType(jObj.getString("customer_type"));
							record.setMoneyInOut(jObj.getString("moneyInOut"));
							record.setPayReceNo(jObj.getString("payReceNo"));
							record.setPlacementSheet(sheet);
							sheetRecords.add(record);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				sheet.setPlacementSheetRecords(sheetRecords);

				Object object = daoImpl.updatePlacementSheet(sheet);
				if (object instanceof PlacementSheet) {
					placementSheetDto.setSuccess(true);
					placementSheetDto.setResulteMsg("SUCCESS");
				} else {
					placementSheetDto.setSuccess(false);
					placementSheetDto.setResulteMsg("There is some error returned from the server.");
				}
			} else {
				placementSheetDto.setSuccess(false);
				placementSheetDto.setResulteMsg("There is some error returned from the server.");
			}

		} catch (ParseException e1) {
			e1.printStackTrace();
		}

	}

	public List<PlacementSheetDto> getPlacementByFund(String date, int fundid) {
		List<PlacementSheetDto> dtos = new ArrayList<PlacementSheetDto>();
		try {
			PlacementSheet placementSheet = daoImpl.getPlacementSheetByFundDate(fundid, format.parse(date));
			if (placementSheet != null) {
				PlacementSheetDto dto = new PlacementSheetDto();
				dto.setDate(format.format(placementSheet.getDate()));
				dto.setFund(placementSheet.getFund().getId());
				dto.setId(placementSheet.getId());
				dto.setStatus(placementSheet.getStatus());
				dtos.add(dto);
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}
		return dtos;
	}

	public void confirmPlacement(int plasementsheetid, PlacementSheetDto placementSheetDto) {
		PlacementSheet sheet = daoImpl.getPlacementSheetById(plasementsheetid);
		if (sheet != null) {
			sheet.setStatus("CONFIRM");
			Object object = daoImpl.confirm(sheet);
			if (object instanceof PlacementSheet) {
				placementSheetDto.setSuccess(true);
				placementSheetDto.setResulteMsg("SUCCESS");
			} else {
				placementSheetDto.setSuccess(false);
				placementSheetDto.setResulteMsg("There is some error returned from the server.");
			}
		}

	}

	public void rejectPlacement(int plasementsheetid, PlacementSheetDto placementSheetDto) {
		PlacementSheet sheet = daoImpl.getPlacementSheetById(plasementsheetid);
		if (sheet != null) {
			sheet.setStatus("REJECT");
			Object object = daoImpl.confirm(sheet);
			if (object instanceof PlacementSheet) {
				placementSheetDto.setSuccess(true);
				placementSheetDto.setResulteMsg("SUCCESS");
			} else {
				placementSheetDto.setSuccess(false);
				placementSheetDto.setResulteMsg("There is some error returned from the server.");
			}
		}
	}

}
